package com.swjd.sell.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.swjd.sell.dao.ProductInfoDao;
import com.swjd.sell.dto.StockDTO;
import com.swjd.sell.exception.SellException;
import com.swjd.sell.pojo.ProductInfo;
import com.swjd.sell.pojo.enums.ProductStatusEnum;
import com.swjd.sell.pojo.enums.ResultEnum;
import com.swjd.sell.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 刘涛
 * @create 2021/8/23 20:59
 */
@Service
public class ProductInfoServiceImpl implements ProductInfoService {
    @Autowired
    private ProductInfoDao productInfoDao;

    @Override
    public ProductInfo selectById(String productId) {
        ProductInfo productInfo = productInfoDao.selectById(productId);
        return productInfo;
    }

    @Override
    public List<ProductInfo> selectUpAll() {
        //传入枚举类型的UP即0
        List<ProductInfo> allUpProduct = productInfoDao.findAllByProductStatus(ProductStatusEnum.UP.getValue());
        return allUpProduct;
    }

    @Override
    public IPage<ProductInfo> selectAll(IPage iPage) {
        //查询所有商品信息并进行分页
        IPage selectPage = productInfoDao.selectPage(iPage, null);
        return selectPage;
    }

    @Override
    public Integer add(ProductInfo productInfo) {
        int i = productInfoDao.insert(productInfo);
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void increaseStock(List<StockDTO> stockDTOS) {
        for (StockDTO stockDTO : stockDTOS) {
            ProductInfo productInfo = new ProductInfo();
            productInfo.setProductId(stockDTO.getProductId());
            //根据id查询库存
            ProductInfo productInfo1 = productInfoDao.selectById(stockDTO.getProductId());
            if (productInfo1 == null) {
                throw new SellException(ResultEnum.PROTECTED_NOT_EXIT);
            }
            //将订单产品数量加上现有库存
            productInfo.setProductStock(stockDTO.getProductQuantity()+productInfo1.getProductStock());
            productInfoDao.updateById(productInfo);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reduceStock(List<StockDTO> stockDTOS) {
        for (StockDTO stockDTO : stockDTOS) {
            ProductInfo productInfo = productInfoDao.selectById(stockDTO.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PROTECTED_NOT_EXIT);
            }
            Integer i = productInfo.getProductStock() - stockDTO.getProductQuantity();
            if (i < 0) {
                throw new SellException(ResultEnum.PROTECTED_STOCK_ERROR);
            }
            productInfo.setProductStock(i);
            productInfoDao.updateById(productInfo);
        }
    }
}
